<?php
class Admin_OrdersController extends Zend_Controller_Action
{
    private $_model = null;
    private $_model1 = null;
    public function init()
    {
        /* Initialize action controller here */
        $this->_model = new Application_Model_DbTable_Order();
        $this->_model1= new Application_Model_DbTable_OrderHistory();
    }
    public function indexAction()
    {
        /*
        // action body
        $choice = $this->_request->getParam("choice");
        if(!empty($choice)){
            $id = intval($this->_request->getParam("id"));
            $result = $this->_model->changeType($choice, $id);
            $this->_helper->json->sendJson($result);
        }
        */
    }
    public function listAction()
    {
        
         $sortby = $this->_request->getParam("sortby",null);
         $sorttype = $this->_request->getParam("sorttype", "asc");
         $filter_field = $this->_request->getParam("filter_field", null);
         $filter_value = $this->_request->getParam("filter_value");
         $this->view->sort = array("by"=>$sortby, "type"=>$sorttype);
         
         $filter = null;
         if(!empty($filter_field))
         {
            $filter[$filter_field] = $filter_value;
         }
        // print_r($filter);
        
         $adapter = $this->_model->fetchPaginatorAdapter($filter,$sortby,$sorttype);
         
         //print_r($adapter);
         
         $paginator = new Zend_Paginator($adapter);
         //Show 2 dòng trên 1 trang
         $paginator->setItemCountPerPage(10);
         //Nhận giá trị phân trang page với giá trị mặc định bằng 1
         $page = $this->_request->getParam("page",1);
         //Xác định trang đang được chọn
         $paginator->setCurrentPageNumber($page);
         //Đổ dữ liệu vào view
         $this->view->datas = $paginator;
         //Vì load ajax không load layout
         $this->_helper->layout()->disableLayout();
         $this->getResponse()->clearBody();
         
    }
    
    public function detailAction(){
            $this->view->headScript()->appendFile(
            $this->view->baseUrl("templates/admin/js/fancy-button/fancy-button.js")
        );
        $this->view->headLink()->prependStylesheet(
            $this->view->baseUrl("templates/admin/css/fancy-button/fancy-button.css")
        );
        $id = $this->_request->getParam("id", null);
        $result=null;
        if($id!=null){
            $row=$this->_model->find($id)->current();
            $this->view->data=$row;
            $oderdetail =new Application_Model_DbTable_OrderDetail();
            /*
            $modelproduct=new Application_Model_DbTable_Product();
            $product_list=array();
            */
            
            // Lấy danh sách chi tiết các dòng với điều kiện orders_id=$id
            
           /*
           
            $rowsdetail=$oderdetail->fetchAll("orders_id=$id");
            foreach($rowsdetail as $row){
                $product_list[]=$modelproduct->find($row->products_id)->current();
            }
            $this->view->productlist=$product_list;
            $this->view->rowsdetail=$rowsdetail;
            
            */
            $select=$oderdetail->select();
            $select->from(array("dt"=>"order_details"),array("qty"=>"dt.qty"))
                ->join(array("pro"=>"products"),"pro.id=dt.products_id",array("code"=>"pro.code","name"=>"pro.name","thumb"=>"pro.thumb","price"=>"pro.price"))
                ->where("orders_id=$id")
                ->setIntegrityCheck(false);
                $this->view->productlist=$oderdetail->fetchAll($select);
                
            //Nhúng form từ thư việc form được tạo
            $form= new Application_Form_Order();
            $modelstatus = new Application_Model_DbTable_OrderStatus();
            $rowmodelstatus = $modelstatus->fetchAll();
             $modelhistory=new Application_Model_DbTable_OrderHistory();
            //start

            $selecthistory=$modelhistory->select();
            $selecthistory->from(array("os"=>"order_status"),array("name"=>"os.name"))
                          ->join(array("oh"=>"order_history"),"os.status_id=oh.status_id",array("date"=>"oh.date","comment"=>"oh.comment","notify_customer"=>"oh.notify_customer"))
                          ->where("orders_id=$id")
                          ->setIntegrityCheck(false);
            $this->view->datasss=$modelhistory->fetchAll($selecthistory);      
            
            //$roworderhistory=$modelhistory->fetchAll("orders_id=$id"); 
            //$this->view->datasss=$roworderhistory;
            

            //var_dump($roworderhistory);  
            //end
            foreach($rowmodelstatus as $row_status){
                $form->status_id->addMultiOptions(array($row_status->status_id=>$row_status->name));
            }
            //xét orders_id
            $form->orders_id->setValue($id);
            if($this->_request->isPost())
            {
                //Nếu như nhận được giá trị sau khi submit
                if($form->isValid($_POST))
                {
                        //đổ dữ liệu vào biến $data
                        $data = $form->getValues();                
                        $nrow=$modelhistory->createRow($data);
                        
                        $nrow->date=date("Y-m-d H:i:s");
                        $nid=$nrow->save();
                        $this->view->message = "Successfull"; 
                        
                        if($nrow->notify_customer){
                            
                            $subject="tvoshopee.com notice";
                            $mailbody="Bill be changed by admin";
                            
                            $smtpServer = 'smtp.gmail.com';
                            $username = 'kiet.vo@non.vn';
                            $password = 'k20460077';
                            $config = array('ssl' => 'tls',
                                            'auth' => 'login',
                                            'username' => $username,
                                            'password' => $password);
                            
                            $transport = new Zend_Mail_Transport_Smtp($smtpServer, $config);
                            $mail = new Zend_Mail('utf-8');
                            $mail->setFrom($username, ' ');
                            $mail->addTo($row->email, "Cám ơn quý khách hàng đã mua hàng tại thegioisach24h.com");
            				//$mail->addTo("sachmiennam@thegioisach24h.com","Khách hàng đặt sách.");
                            $mail->setSubject($subject);
                            $mail->setBodyHtml($mailbody,'utf-8');
                            $mail->send($transport);
                        } 
                }             
            }
        }
        $this->view->form = $form;        
    }
    public function delAction()
    {
        $id = $this->_request->getParam("id", null);
        $result = null;
        if($id!=null)
        {
            $row = $this->_model->find($id)->current();
            $imagePath = APPLICATION_PATH."/../public/images/product/";
            if(is_file($imagePath."$row->image")){
                unlink($imagePath.$row->image);
            }
            $thumbPath = $imagePath."thumb/";
            if(is_file($thumbPath.$row->thumb)) {
                unlink($thumbPath.$row->thumb);
            }
            $result = $row->delete();
        }
        $this->_helper->json->sendJson($result);
    }
}